package service

import (
	"context"
	"time"
	"user-srv/basic/config"
	__ "user-srv/basic/proto"
	"user-srv/handler/model"
	"user-srv/pkg"
)

type Server struct {
	__.UnimplementedUserServer
}

func (s *Server) CreateUser(_ context.Context, in *__.CreateUserReq) (*__.CreateUserResp, error) {
	var user model.User

	err := user.GetUserByMobile(in.Mobile)
	if err != nil {
		return nil, err
	}

	if user.Id > 0 {
		return nil, err
	}

	get := config.RDB.Get(config.Ctx, "sendSms"+in.Mobile+"register")

	if get.Val() != in.Sms {
		return nil, err
	}

	code6 := pkg.Code6()

	user = model.User{
		Mobile:   in.Mobile,
		Password: pkg.Md5(in.Password + code6),
		Salt:     code6,
	}

	err = user.CreateUser()
	if err != nil {
		return nil, err
	}

	return &__.CreateUserResp{UserId: int64(user.Id)}, nil
}

func (s *Server) SendSms(_ context.Context, in *__.SendSmsReq) (*__.SendSmsResp, error) {

	code6 := pkg.Code6()

	//log.Println(in.Mobile, code6)

	//pkg.SendSms(in.Mobile, code6)

	config.RDB.Set(config.Ctx, "sendSms"+in.Mobile+in.Source, code6, time.Minute*5)

	return &__.SendSmsResp{}, nil
}

func (s *Server) LoginUser(_ context.Context, in *__.LoginUserReq) (*__.LoginUserResp, error) {

	var user model.User

	err := user.GetUserByMobile(in.Mobile)
	if err != nil {
		return nil, err
	}

	if user.Id == 0 {
		return nil, err
	}

	if user.Password != pkg.Md5(in.Password+user.Salt) {
		return nil, err
	}

	token := pkg.CreateJwtToken(int32(user.Id))

	return &__.LoginUserResp{Token: token}, nil
}
